package cn.i7baozh.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 全局自定义过滤器
 * 实现一个接口完成所需时间日志打印
 *
 * @author zhangbaoqi532
 * @date 2024/12/27
 */
@Component
public class MyCustomGlobalFilter implements GlobalFilter, Ordered {

    private static final String BEGIN_TIME_I7BAOZH = "begin_time_i7baozh";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        exchange.getAttributes().put(BEGIN_TIME_I7BAOZH, System.currentTimeMillis());

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(BEGIN_TIME_I7BAOZH);
            if (startTime != null) {
                URI uri = exchange.getRequest().getURI();
                String host = uri.getHost();
                System.out.println("host:" + uri.getHost());
                System.out.println("port:" + uri.getPort());
                System.out.println("path:" + uri.getPath());
                System.out.println("参数:" + uri.getRawQuery());
                System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + "毫秒");
            }
        }));
    }

    /**
     * 值越小 越靠前
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
